package com.foreveross.chameleon.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class FilePathPlugin extends CordovaPlugin {
	private static final String TAG="FilePathPlugin";
	private static final int FILE_CHOOSE_CODE = 10;
	private CallbackContext callbackContext;

	@Override
	public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext)
			throws JSONException {
		this.callbackContext=callbackContext;
		if (action != null && args != null) {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("*/*");
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			try {
				cordova.startActivityForResult(this, Intent.createChooser(intent, "文件管理器"),
						FILE_CHOOSE_CODE);
				PluginResult pluginResult = new PluginResult(Status.NO_RESULT);
				pluginResult.setKeepCallback(true);
				callbackContext.sendPluginResult(pluginResult);
			} catch (android.content.ActivityNotFoundException ex) {
				callbackContext.error("系统未安装文件管理");
			}

		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == FILE_CHOOSE_CODE) {
			if (resultCode == Activity.RESULT_OK) {
				Uri uri = intent.getData();
				String path = getPath(cordova.getActivity(), uri);
				Log.v(TAG,"path>>"+path);
				callbackContext.success(path);
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	public String getPath(Context context, Uri uri) {

		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
				// Eat it
			}
		}

		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

}
